/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.edu.utfpr.servlet;

import br.edu.utfpr.dao.Dao;
import br.edu.utfpr.model.Equipe;
import br.edu.utfpr.model.Pais;
import br.edu.utfpr.model.Piloto;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author andre
 */
@WebServlet(name = "PilotoServlet", urlPatterns = {"/PilotoServlet"})
public class PilotoServlet extends HttpServlet {

    private String op;
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
          op = request.getParameter("op");

        if (op.equals("find")) {
            Dao<Piloto> dao = new Dao<Piloto>(Piloto.class);
            Piloto piloto = dao.obter(Integer.parseInt(request.getParameter("id")));
            if (piloto != null) {
                request.getSession().setAttribute("piloto", piloto);
                response.sendRedirect("edPiloto.jsp");
            } else {
                request.getSession().setAttribute("msg", "Piloto inexistente");
                response.sendRedirect("piloto.jsp");
            }
        } else if (op.equals("remove")) {
            Dao<Piloto> dao = new Dao<Piloto>(Piloto.class);
            dao.remover(Integer.parseInt(request.getParameter("id")));
            response.sendRedirect("piloto.jsp");
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
         op = request.getParameter("op");
        String nome = request.getParameter("nome");
        int paisId = Integer.parseInt(request.getParameter("pais_id"));
        int equipeId = Integer.parseInt(request.getParameter("equipe_id"));
        
        Dao<Piloto> dao = new Dao<Piloto>(Piloto.class);

        if (op.equals("insert")) {
            Piloto p = new Piloto();
            p.setNome(nome);
            p.setPais(new Dao<Pais>(Pais.class).obter(paisId));
            p.setEquipe(new Dao<Equipe>(Equipe.class).obter(equipeId));
            p.setStatus(request.getParameter("status")!=null);
            dao.inserir(p);
        } else if (op.equals("update")) {
            Piloto p = (Piloto) request.getSession().getAttribute("piloto");
            p.setNome(nome);
            p.setPais(new Dao<Pais>(Pais.class).obter(paisId));
            p.setEquipe(new Dao<Equipe>(Equipe.class).obter(equipeId));
            p.setStatus(request.getParameter("status")!=null);
            dao.atualizar(p);
            request.getSession().removeAttribute("piloto");
        }
        response.sendRedirect("piloto.jsp");
    }
}
